// @flow
import React from 'react'
import { Tree } from 'antd'
const TreeNode = Tree.TreeNode
// const Search = Input.Search

const dataList = []
const generateList = (data) => {
  for (let i = 0; i < data.length; i++) {
    const node = data[i]
    const key = node.key
    dataList.push({ key, title: key })
    if (node.children) {
      generateList(node.children, node.key)
    }
  }
}

const getParentKey = (key, tree) => {
  let parentKey
  for (let i = 0; i < tree.length; i++) {
    const node = tree[i]
    if (node.children) {
      if (node.children.some(item => item.key === key)) {
        parentKey = node.key
      } else if (getParentKey(key, node.children)) {
        parentKey = getParentKey(key, node.children)
      }
    }
  }
  return parentKey
}
type Props = {
  treeData: Array<Object>,
  onChange: Function,
  defaultValue: Array<Object>,
  expandedKeys: string,
  setCurrentVaule: Function
}

type State = {
  expandedKeys: Array<any>,
  searchValue: string,
  autoExpandParent: boolean,
  gData: Array<Object>,
  checkedKeys: Array<string>,
  uselessKey: string,
}

class SelectTree extends React.Component {
  props: Props
  state: State
  onCheck: Function
  onSelect: Function
  onExpand: Function
  onChange: Function
  nodeCheckoutArr: Array<Object>
  constructor (props: Object) {
    super(props)
    this.state = {
      expandedKeys: [this.props.expandedKeys],
      searchValue: '',
      autoExpandParent: true,
      gData: this.props.treeData,
      checkedKeys:this.props.defaultValue[0] ? this.props.defaultValue[0].key : [],
      uselessKey: ''
    }
    this.onCheck = this.onCheck.bind(this)
    this.onSelect = this.onSelect.bind(this)
    this.onExpand = this.onExpand.bind(this)
    this.onChange = this.onChange.bind(this)
  }

  componentDidMount () {
    const { gData } = this.state
    generateList(gData)
    this.props.onChange(this.props.defaultValue)
  }
  onExpand = (expandedKeys: Array<string>, node: Object) => {
    this.setState({
      expandedKeys: []
    })
    if (node.expanded) {
      // const eventKey = node.node.props.eventKey
      // const type = node.node.props.children[0].props.sensorType || ''
      this.setState({
        expandedKeys: [node.node.props.eventKey]
      })
      // 请求该测点的通道ID
      // this.props.getOptions(eventKey, type)
    }
  }
  onChange = (e: Object) => {
    const { gData } = this.state
    const value = e.target.value
    const expandedKeys = dataList.map((item) => {
      if (item.key.indexOf(value) > -1) {
        return getParentKey(item.key, gData)
      }
      return null
    }).filter((item, i, self) => item && self.indexOf(item) === i)
    this.setState({
      expandedKeys,
      searchValue: value,
      autoExpandParent: true
    })
  }
  onSelect = (selectedKeys: Array<string>, info: Object) => {
    // console.log('selected', selectedKeys, info)
  }
  onCheck = (checkedKeys: Array<string>, info: Object) => {
    // console.log('onCheck', checkedKeys, info)
    // 小于5个值
    // const uselessKey = info.node.props.eventKey
    // this.props.setCurrentVaule(uselessKey, this.state.uselessKey)
    // if (this.state.uselessKey) {
    //   checkedKeys = checkedKeys.filter(item => item !== this.state.uselessKey)
    // }
    // if (checkedKeys.length <= 5) {
    //   this.setState({ checkedKeys })
    // } else {
    //   this.setState({ uselessKey })
    // }
    console.log(this.state.gData)
    const gDataArr = this.state.gData.filter(item => item.key === '振动量')
    let nodeArr = []
    let addKeys = []
    let removeKeys = []
    gDataArr.length !== 0 && gDataArr[0].children.forEach(item => { // 选中
      checkedKeys.forEach(key => {
        if ((key.indexOf(item.key.substring(1, 3)) !== -1 && !isNaN(item.key.substring(1, 2)))) {
          if (info.checked) {
            addKeys.push(item.sensorNameEn + '___' + item.key)
            nodeArr = gDataArr[0].children // 联动选中
            .filter(node => (node.key.indexOf(info.node.props.eventKey.substring(9, 10)) !== -1 &&
            !isNaN(info.node.props.eventKey.substring(9, 10))))
          } else {
            if (!isNaN(info.node.props.eventKey.substring(9, 10))) {
              removeKeys.push(...checkedKeys
                .filter(node => (node.indexOf(info.node.props.eventKey.substring(9, 10)) !== -1)))
            }
          }
        }
      })
    })
    const newCheckedKeys = checkedKeys
      .filter(key => !removeKeys.includes(key))
      .concat(addKeys)
    if (!info.checked) { // 取消选中
      let nodeArrO = []
      let nodeArrT = []
      let nodeArrR = []
      if (!isNaN(info.node.props.eventKey.substring(9, 10))) { // 联动的情况
        this.nodeCheckoutArr.map(item => {
          if (item.props === undefined) {
            nodeArrO = this.nodeCheckoutArr
            .filter(node =>
              (node.key.indexOf(info.node.props.eventKey.substring(9, 10)) === -1))
          } else {
            nodeArrT = this.nodeCheckoutArr
            .filter(node =>
              (node.key.indexOf(info.node.props.eventKey.substring(9, 10)) === -1))
          }
        })
      } else { // 普通情况
        nodeArrR = this.nodeCheckoutArr !== undefined ? this.nodeCheckoutArr
        .filter(node => node.key.indexOf(info.node.props.eventKey) === -1) : []
      }
      nodeArr = nodeArrO.concat(nodeArrT).concat(nodeArrR)
    }
    const newKeyArr = []
    const keyJson = {}
    for (var k = 0; k < newCheckedKeys.length; k++) {
      if (!keyJson[newCheckedKeys[k]]) {
        newKeyArr.push(newCheckedKeys[k])
        keyJson[newCheckedKeys[k]] = 1
      }
    }
    this.setState({ checkedKeys: newKeyArr })
    let newInfo = info.checkedNodes
    if (info.checked) {
      newInfo = info.checkedNodes.concat(nodeArr)
    } else {
      newInfo = nodeArr
    }
    this.nodeCheckoutArr = newInfo // 取消选中用的数据
    const checkedNodes = newInfo.map((d, i) => {
      if (d.props !== undefined) {
        return { key: d.key, En: d.props.sensorNameEn, keyName: d.props.keyName, sensorType: d.props.sensorType }
      } else {
        return { key: d.sensorNameEn + '___' + d.key, En: d.sensorNameEn, keyName: d.keyName, sensorType: d.sensorType }
      }
    })
    var hash = {}
    var i = 0
    var res = []
    const nodesArr = []
    const infoJson = {}
    for (var f = 0; f < checkedNodes.length; f++) {
      if (!infoJson[checkedNodes[f].key]) {
        nodesArr.push(checkedNodes[f])
        infoJson[checkedNodes[f].key] = 1
      }
    }
    nodesArr.forEach(function (item) {
      var En = item.En
      if (En) {
        hash[En]
        ? res[hash[En] - 1].key.push(item.key) && res[hash[En] - 1].keyName.push({ key:item.key, name: item.keyName })
        : hash[En] = ++i && res.push({
          key: [item.key],
          keyName: [{ key:item.key, name: item.keyName }],
          sensorType: item.sensorType,
          En: En
        })
      }
    })
    this.props.onChange(res)
  }
  render () {
    // const { searchValue, expandedKeys, autoExpandParent, gData } = this.state
    const { searchValue, gData, expandedKeys, checkedKeys } = this.state
    // console.log(this.props.treeData)
    const loop = data => data.map((item) => {
      if (item) {
        const index = item.title.search(searchValue)
        const beforeStr = item.title.substr(0, index)
        const afterStr = item.title.substr(index + searchValue.length)
        const title = index > -1 ? (
          <span>
            {beforeStr}
            <span style={{ color: '#f50' }}>{searchValue}</span>
            {afterStr}
          </span>
        ) : <span>{item.title}</span>
        if (item.children) {
          return (
            <TreeNode key={item.sensorNameEn + '___' + item.key} title={title}
              // disableCheckbox
              keyName={item.keyName} sensorNameEn={item.sensorNameEn} sensorType={item.sensorType}>
              {loop(item.children)}
            </TreeNode>
          )
        }
        return <TreeNode key={item.sensorNameEn + '___' + item.key}
          keyName={item.keyName} title={title} sensorNameEn={item.sensorNameEn} sensorType={item.sensorType} />
      }
    })
    return (
      <div>
        {
          // <Search placeholder='搜索...' onChange={this.onChange} />
        }
        <Tree
          checkedKeys={checkedKeys}
          checkable
          // defaultExpandAll
          defaultCheckedKeys={this.props.defaultValue[0] ? this.props.defaultValue[0].key : []}
          onSelect={this.onSelect}
          onCheck={this.onCheck}
          onExpand={this.onExpand}
          expandedKeys={expandedKeys}
          // autoExpandParent={autoExpandParent}
        >
          {
            loop(gData)
          }
        </Tree>
      </div>
    )
  }
}
export default SelectTree
